<template>
  <div class="box">
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 警告区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"> </el-alert>  
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
          <el-col>
              <span>选择商品分类：</span>
              <!-- 选择商品分类级联选择框 -->
              <!-- options 数据源 props 指定配置对象-->
              <el-cascader clearable change-on-select v-model="selectKeys" :options="cateList" :props="cascadeProps" @change="cateChanged"></el-cascader>
          </el-col>
      </el-row>
      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTabName" border stripe style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand"  width="50">
              <template slot-scope="scope">
                <el-tag closable @close="removeParamsValue(scope.row,i)" v-for="(item, i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>              
              </template>            
            </el-table-column>
            <el-table-column type="index" label="序号" width="50"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作" width="300px" >
              <template slot-scope="scope">
                <!-- 修改 -->
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="btnEditParams(scope.row.attr_id)">编辑
                </el-button>
                <!-- 删除 -->
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="btnDeleteParams(scope.row.attr_id)">
                    删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTabName" border stripe style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand"  width="50">
              <template slot-scope="scope">
                <el-tag closable @close="removeParamsValue(scope.row,i)" v-for="(item, i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>              
              </template>            
            </el-table-column>
            <el-table-column type="index" label="序号" width="50"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改 -->
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="btnEditParams(scope.row.attr_id)">编辑
                </el-button>
                <!-- 删除 -->
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="btnDeleteParams(scope.row.attr_id)">
                    删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加动态参数/静态属性对话框 -->
      <el-dialog
        :title="'添加' + titleText"
        :visible.sync="addDialogVisible"
        width="40%"
        @close="addDialogClosed">
        <!-- 内容主题区 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px" class="demo-ruleForm">
          <!-- prop 是验证规则 -->
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>  
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="btnSaveAdd">确 定</el-button>
        </span>
      </el-dialog>      
      <!-- 修改动态参数/静态属性对话框 -->
      <el-dialog
        :title="'修改' + titleText"
        :visible.sync="editDialogVisible"
        width="40%"
        @close="editDialogClosed">
        <!-- 内容主题区 -->
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px" class="demo-ruleForm">
          <!-- prop 是验证规则 -->
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>  
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="btnSaveEdit">确 定</el-button>
        </span>
      </el-dialog>       
    </el-card>   
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 分类列表
      cateList: [],
      // 级联选择器选中的分类
      selectKeys: [],
      // 级联选择器的配置
      cascadeProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
      },
      // tab 页签绑定激活的值
      activeName: "many",
      // 动态参数列表
      manyTabName: [],
      // 静态属性列表
      onlyTabName: [],
      // 添加对话框是否打开
      addDialogVisible: false,
      // 添加动态参数/静态属性表单
      addForm: {
        // 动态参数/静态属性
        attr_name: "",
      },
      addFormRules: {
        // 验证动态参数/静态属性是否合法
        attr_name: [
          {
            required: true,
            message: "请输入参数名称",
            trigger: "blur",
          },
        ],
      },
      // 修改对话框是否打开
      editDialogVisible: false,
      // 修改动态参数/静态属性表单
      editForm: {
        // 动态参数/静态属性
        attr_name: "",
      },
      editFormRules: {
        // 验证动态参数/静态属性是否合法
        attr_name: [
          {
            required: true,
            message: "请输入参数名称",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取所有分类列表 type等于3
    async getCateList() {
      // get 方法返回一个 promise 对象
      // 不携带任何参数
      const { data: res } = await this.$axios.get("categories");
      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
      this.cateList = res.data;
    },
    // 级联选择器选择项发生变化时触发
    // 只允许选中三级分类，不允许选中一二级
    cateChanged() {
      // 证明选中了一二级分类
      if (this.selectKeys.length != 3) {
        this.selectKeys = [];
        this.manyTabName = [];
        this.onlyTabName = [];
        return;
      } else {
        this.getParamsList();
      }
    },
    handleTabClick() {
      this.getParamsList();
    },
    async getParamsList() {
      // get 返回值为promise 因此用异步async/await
      const { data: res } = await this.$axios.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      );
      // 获取失败
      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg);
      }
      // 获取成功
      this.$message.success(res.meta.msg);
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // 控制 tag 文本框的显示与隐藏
        item.inputVisible = false;
        // 文本框中输入的值
        item.inputValue = "";
      });
      if (this.activeName == "many") {
        this.manyTabName = res.data;
      } else {
        this.onlyTabName = res.data;
      }
    },
    // 添加界面确定按钮
    btnSaveAdd() {
      // 表单验证成功 valid 为 true
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        // 发起网络请求添加角色
        // post 返回值为promise 因此用异步async/await
        const { data: res } = await this.$axios.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        // 添加失败
        if (res.meta.status != 201) {
          return this.$message.error(res.meta.msg);
        }
        // 添加成功
        this.$message.success(res.meta.msg);
        // 关闭对话框
        this.addDialogVisible = false;
        // 刷新数据
        this.getParamsList();
      });
    },
    addDialogClosed() {
      // 清空表单
      this.$refs.addFormRef.resetFields();
    },
    // 编辑界面确定按钮
    btnSaveEdit() {
      // 表单验证成功 valid 为 true
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        // 发起网络请求修改参数
        // put 返回值为promise 因此用异步async/await
        const { data: res } = await this.$axios.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        );
        // 修改失败
        if (res.meta.status != 200) {
          return this.$message.error(res.meta.msg);
        }
        // 修改成功
        this.$message.success(res.meta.msg);
        // 关闭对话框
        this.editDialogVisible = false;
        // 刷新数据
        this.getParamsList();
      });
    },
    editDialogClosed() {
      // 清空表单
      this.$refs.editFormRef.resetFields();
    },
    // 删除参数
    btnDeleteParams(attrId) {
      this.$confirm("此操作将永久删除该参数, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 发起删除的网络请求
          const { data: res } = await this.$axios.delete(
            `categories/${this.cateId}/attributes/${attrId}`
          );
          // 删除失败
          if (res.meta.status != 200) {
            return this.$message.error(res.meta.msg);
          }
          // 删除成功
          this.$message.success(res.meta.msg);
          // 刷新数据
          this.getParamsList();
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 编辑参数
    async btnEditParams(attrId) {
      // 根据 id 发起网络请求获取信息
      // get 返回值为promise 因此用异步async/await
      const { data: res } = await this.$axios.get(
        `categories/${this.cateId}/attributes/${attrId}`,
        { params: { attr_sel: this.activeName } }
      );
      // 请求失败
      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg);
      }
      // 请求成功
      this.$message.success(res.meta.msg);
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    // 点击按钮 展示文本输入框
    showInput(row) {
      row.inputVisible = true;
      // 让文本框自动获得焦点
      // $nextTick 方法的作用：当页面上的元素重新被渲染之后 才会执行回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 文本框失去焦点或者按下 enter 时触发
    handleInputConfirm(row) {
      if (row.inputValue.trim().length == 0) {
        return;
      } else {
        row.attr_vals.push(row.inputValue.trim());
      }
      row.inputValue = "";
      row.inputVisible = false;
      this.modifyParams(row);
    },
    // 删除参数值
    removeParamsValue(row, i) {
      // splice 会直接操作原数组
      row.attr_vals.splice(i, 1);
      this.modifyParams(row);
    },
    async modifyParams(row) {
      // 发起网络请求 将添加/删除的内容上传至数据库中
      // put 返回值为promise 因此用异步async/await
      const { data: res } = await this.$axios.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      // 修改失败
      if (res.meta.status != 200) {
        return this.$message.error(res.meta.msg);
      }
      // 修改成功
      this.$message.success(res.meta.msg);
    },
  },
  // 计算属性
  computed: {
    // 如果级联选择器没有选中第三级分类 则让 tab 按钮禁用
    // 如果按钮需要被禁用则返回 true
    isBtnDisabled() {
      if (this.selectKeys.length != 3) {
        // 禁用
        return true;
      } else {
        // 不禁用
        return false;
      }
    },
    // 当前选中的三级分类的 id
    cateId() {
      if (this.selectKeys.length == 3) {
        return this.selectKeys[2];
      }
      return null;
    },
    // 动态计算添加动态参数/静态属性的文本
    titleText() {
      if (this.activeName == "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
  },
};
</script>

<style scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin-left: 7px;
}
.button-new-tag {
  margin-left: 7px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 7px;
  vertical-align: bottom;
}
</style>>